/* Copyright (c) 2016-2020 Enfry Ltd. All Rights Reserved.
 * 
 * This software is the confidential and proprietary information of Enfry. 
 * You shall not disclose such Confidential Information
 * and shall use it only in accordance with the terms of the agreements
 * you entered into with Enfry.
 */
package com.enfry.storage.interceptor;

import java.io.IOException;
import java.util.LinkedHashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.enfry.storage.interceptor.IProcessor;
import com.enfry.storage.interceptor.StorageApiInterceptor;

/**
 * API第三方调用拦截器。
 * @Title com.enfry.storage.interceptor.StorageApiInterceptor
 * @author liulei
 * @date 2016年7月25日
 */
public class StorageApiInterceptor extends HandlerInterceptorAdapter {
    private static Logger logger = LoggerFactory.getLogger(StorageApiInterceptor.class);
    private LinkedHashMap<String, IProcessor[]> processors;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        logger.debug("API拦截：" + request.getRequestURI() + ", ContextPath=" + request.getContextPath());
        String path = request.getRequestURI().replaceFirst(request.getContextPath(), "");

        IProcessor[] processorArr = processors.get(path);

        if(processorArr == null) return false;

        boolean result = true;
        for (int i = 0; i < processorArr.length && result; i++) {
            IProcessor processor = processorArr[i];
            String reqApiName = path.substring(1);
            logger.debug("API拦截处理, apiName: " + reqApiName + ", processor: " + processor.getClass().getSimpleName());
            result = processor.process(request, response, handler, reqApiName);
        }
        return result;
    }

    public LinkedHashMap<String, IProcessor[]> getProcessors() {
        return processors;
    }

    public void setProcessors(LinkedHashMap<String, IProcessor[]> processors) {
        this.processors = processors;
    }
    
}
